/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.material.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springblade.common.annotation.ServiceLog;
import org.springblade.common.constant.TrainingOperateConstant;
import org.springblade.common.enums.library.QuestionType;
import org.springblade.core.excel.util.ExcelUtil;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.CollectionUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.library.service.IQuestionBankService;
import org.springblade.modules.library.service.IQuestionOptionService;
import org.springblade.modules.library.vo.QuestionBankVO;
import org.springblade.modules.material.bo.PaperBO;
import org.springblade.modules.material.entity.PaperDetailEntity;
import org.springblade.modules.material.excel.PaperImportExcel;
import org.springblade.modules.material.excel.PaperImporter;
import org.springblade.modules.material.service.IPaperDetailService;
import org.springblade.modules.material.vo.GetPaperVO;
import org.springblade.modules.material.vo.PaperDetailVO;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.modules.material.entity.PaperEntity;
import org.springblade.modules.material.vo.PaperVO;
import org.springblade.modules.material.wrapper.PaperWrapper;
import org.springblade.modules.material.service.IPaperService;
import org.springblade.core.boot.ctrl.BladeController;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.springblade.common.cache.TrainingCacheName.PAPER_TEMPORARY_CACHE;


/**
 * 试卷表 控制器
 *
 * @author
 * @since 2023-03-22
 */
@RestController
@AllArgsConstructor
@RequestMapping("blade-paper/paper")
@Api(value = "试卷表", tags = "试卷表接口")
public class PaperController extends BladeController {

	private final IPaperService paperService;

	private final IPaperDetailService paperDetailService;

	private final IQuestionBankService questionBankService;

	private final BladeRedis bladeRedis;

	private final IQuestionOptionService questionOptionService;


	/**
	 * 试卷表 详情
	 */
	//@PreAuth(TrainingRoleConstant.HAS_ROLE_TEACHER)
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入paper")
	public R<PaperVO> detail(PaperEntity paper) {
		PaperEntity detail = paperService.getOne(Condition.getQueryWrapper(paper));
		return R.data(PaperWrapper.build().entityVO(detail));
	}

	/**
	 * 试卷表 分页
	 */
	//@PreAuth(TrainingRoleConstant.HAS_ROLE_TEACHER)
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入paper")
	public R<IPage<PaperVO>> list(PaperEntity paper, Query query) {
		LambdaQueryWrapper<PaperEntity> lambdaQueryWrapper=new LambdaQueryWrapper<>();
		if (StringUtils.isNotBlank(paper.getPaperName()))lambdaQueryWrapper.like(PaperEntity::getPaperName,paper.getPaperName());
		lambdaQueryWrapper.orderByDesc(PaperEntity::getCreateTime);
		IPage<PaperEntity> pages = paperService.page(Condition.getPage(query), lambdaQueryWrapper);
		return R.data(PaperWrapper.build().pageVO(pages));
	}

	/**
	 * 试卷表 自定义分页
	 */
	//@PreAuth(TrainingRoleConstant.HAS_ROLE_TEACHER)
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入paper")
	public R<IPage<PaperVO>> page(PaperVO paper, Query query) {
		IPage<PaperVO> pages = paperService.selectPaperPage(Condition.getPage(query), paper);
		return R.data(pages);
	}


	/**
	 * 试卷表 修改
	 * 查出试卷详情表所有数据 与 修改的数据对比差异，保存差异的数据
	 */
	//@PreAuth(TrainingRoleConstant.HAS_ROLE_TEACHER)
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入paper")
	@Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
	@ServiceLog(value = TrainingOperateConstant.PAPER,operate = TrainingOperateConstant.UPDATE,describe = "修改")
	public R update(@Valid @RequestBody PaperBO bo) {
		//根据试卷id 删除所有试卷详情
		Long paperId =bo.getPaper().getId();
		paperDetailService.remove(Wrappers.<PaperDetailEntity>query().lambda().eq(PaperDetailEntity::getPid,paperId));

		PaperEntity paper = bo.getPaper();

		List<PaperDetailVO> newDetailList = bo.getPaperDetailList();

		boolean isNeedReview = false;
		for (PaperDetailVO entity : newDetailList) {
			entity.setPid(paperId);

			if (entity.getQuestionType().equals(QuestionType.SHORT.getCode())) { //如果有简答题，则需要老师阅卷
				isNeedReview = true;
			}
			//MD5解析
			try {
				entity.setContent(URLDecoder.decode(entity.getContent(), "UTF-8"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			entity.setQuestionBankId(entity.getQuestionId());
			entity.setId(null);
			paperDetailService.save(entity);
		}
		if (isNeedReview) {//判断是否需要老师阅卷
			paper.setIsNeedReview(1);
		}else {
			paper.setIsNeedReview(0);
		}
		paperService.updateById(paper);
		bladeRedis.del(PAPER_TEMPORARY_CACHE + AuthUtil.getUser().getUserId());


		return R.status(paperService.updateById(bo.getPaper()));
	}

	/**
	 * 试卷表 删除
	 */
	//@PreAuth(TrainingRoleConstant.HAS_ROLE_TEACHER)
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	@Transactional(rollbackFor = Exception.class)
	@ServiceLog(value = TrainingOperateConstant.PAPER,operate = TrainingOperateConstant.DELETE,describe = "删除")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		paperDetailService.remove(Wrappers.<PaperDetailEntity>query().lambda().in(PaperDetailEntity::getPid, Func.toLongList(ids)));
		return R.status(paperService.deleteLogic(Func.toLongList(ids)));
	}

	/**
	 * 预览试卷
	 *
	 * @param paper
	 * @return
	 */
	//@PreAuth(TrainingRoleConstant.HAS_ROLE_TEACHER)
	@GetMapping("/get-paper")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "预览试卷及试卷详情", notes = "传入paper(id)")
	public R<GetPaperVO> getPaper(PaperEntity paper) {
		GetPaperVO paperVO = paperService.getPaper(paper);
		//将数据按照题目类型分组 类型里面按照时间升序排序
		if (null != paperVO)
			paperVO.setGetPaperDetailVOList(paperService.sortPaperDetailByQuestionType(paperVO.getGetPaperDetailVOList()));
		return R.data(paperVO);
	}


	/**
	 * 查询题库中的题目及选项
	 */
	//@PreAuth(TrainingRoleConstant.HAS_ROLE_TEACHER)
	@GetMapping("/get-question")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "根据课程相关点查试题", notes = "传入questionBank")
	public R<IPage<QuestionBankVO>> getQuestionOptionPage(QuestionBankVO questionBank, Query query) {
		IPage<QuestionBankVO> pages = questionBankService.getQuestionPage(Condition.getPage(query), questionBank);
		return R.data(pages);
	}


	/**
	 * 提交试卷
	 */
	//@PreAuth(TrainingRoleConstant.HAS_ROLE_TEACHER)
	@PostMapping("/save-paper-all")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "提交试卷", notes = "传入paper")
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	@ServiceLog(value = TrainingOperateConstant.PAPER,operate = TrainingOperateConstant.ADD,describe = "新增试卷")
	public R savePaperAll(@Valid @RequestBody PaperBO bo) {
		PaperEntity paper = bo.getPaper();
		paper.setIsNeedReview(0);
		List<PaperDetailVO> paperDetailList = bo.getPaperDetailList();
		paperService.save(paper);
		if (CollectionUtil.isEmpty(paperDetailList)) return R.success("提交成功");

		boolean isNeedReview = false;
		Long paperId = paper.getId();
		for (PaperDetailVO entity : paperDetailList) {
			entity.setPid(paperId);

			if (entity.getQuestionType().equals(QuestionType.SHORT.getCode())) { //如果有简答题，则需要老师阅卷
				isNeedReview = true;
			}

			//MD5解析
			try {
				entity.setContent(URLDecoder.decode(entity.getContent(), "UTF-8"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			entity.setQuestionBankId(entity.getQuestionId());
			entity.setId(null);
			paperDetailService.save(entity);
		}
		if (isNeedReview) {//判断是否需要老师阅卷
			paper.setIsNeedReview(1);
			paperService.updateById(paper);
		}
		bladeRedis.del(PAPER_TEMPORARY_CACHE + AuthUtil.getUser().getUserId());
		return R.success("提交成功");
	}


	/**
	 * 暂存试卷内容的接口
	 */
	//@PreAuth(TrainingRoleConstant.HAS_ROLE_TEACHER)
	@PostMapping("/temporary-storage-paper")
	@ApiOperationSupport(order = 11)
	@ApiOperation(value = "暂存试卷内容的接口", notes = "传入questionBankVOList")
	public R temporaryStoragePaper(@RequestBody List<QuestionBankVO> questionBankVOList) {
		BladeUser user = AuthUtil.getUser();
		if (ObjectUtils.isEmpty(user)) {
			return R.fail("请先登录");
		}
		bladeRedis.set(PAPER_TEMPORARY_CACHE + user.getUserId(), questionBankVOList);
		return R.success("暂存成功");
	}

	/**
	 * 获取暂存试卷内容的接口
	 */
	//@PreAuth(TrainingRoleConstant.HAS_ROLE_TEACHER)
	@GetMapping("/get-temporary-storage-paper")
	@ApiOperationSupport(order = 12)
	@ApiOperation(value = "获取暂存试卷内容的接口", notes = "无需传入参数")
	public R getTemporaryStoragePaper() {
		BladeUser user = AuthUtil.getUser();
		if (ObjectUtils.isEmpty(user)) {
			return R.fail("请先登录");
		}
		return R.data(bladeRedis.get(PAPER_TEMPORARY_CACHE + user.getUserId()));
	}


	/**
	 * 获取试卷各题型的数量
	 */
	//@PreAuth(TrainingRoleConstant.HAS_ROLE_TEACHER)
	@GetMapping("/question-type-num")
	@ApiOperationSupport(order = 13)
	@ApiOperation(value = "获取试卷各题型的数量", notes = "传入试卷id")
	public R getPaperQuestionTypeNum(Long paperId) {
		List<PaperDetailEntity> paperDetailList = paperDetailService.queryByPaperId(paperId);
//		if (CollectionUtils.isEmpty(paperDetailList)) throw new ServiceException("该试卷没有任何题目!");
		Map<String, Long> map = new HashMap<>();
		map.put(QuestionType.SINGLE.toString(), paperDetailList.stream().filter(item -> item.getQuestionType() == QuestionType.SINGLE.getCode().intValue()).count());
		map.put(QuestionType.MULTIPLE.toString(), paperDetailList.stream().filter(item -> item.getQuestionType() == QuestionType.MULTIPLE.getCode().intValue()).count());
		map.put(QuestionType.JUDGE.toString(), paperDetailList.stream().filter(item -> item.getQuestionType() == QuestionType.JUDGE.getCode().intValue()).count());
		map.put(QuestionType.FILL.toString(), paperDetailList.stream().filter(item -> item.getQuestionType() == QuestionType.FILL.getCode().intValue()).count());
		map.put(QuestionType.SHORT.toString(), paperDetailList.stream().filter(item -> item.getQuestionType() == QuestionType.SHORT.getCode().intValue()).count());
		return R.data(map);
	}
	/**
	 * 批量导入试题
	 */
	//@PreAuth(TrainingRoleConstant.HAS_ROLE_TEACHER)
	@PostMapping("import-paper")
	@ApiOperationSupport(order = 12)
	@ApiOperation(value = "导入试卷", notes = "传入excel")
	@ServiceLog(value = TrainingOperateConstant.PAPER,operate = TrainingOperateConstant.IMPORT,describe = "导入试卷")
	public R importQuestionBank(MultipartFile file) {
		PaperImporter paperImporter = new PaperImporter(questionBankService,questionOptionService,paperService,paperDetailService);
		ExcelUtil.save(file, paperImporter, PaperImportExcel.class);
		return R.success("操作成功");
	}

	/**
	 * 导出模板
	 */
	//@PreAuth(TrainingRoleConstant.HAS_ROLE_TEACHER)
	@GetMapping("export-template")
	@ApiOperationSupport(order = 13)
	@ApiOperation(value = "导出模板")
	public void exportUser(HttpServletResponse response) {
		List<PaperImportExcel> list = new ArrayList<>();
		ExcelUtil.export(response, "试卷模板", "试卷模板", list, PaperImportExcel.class);
	}

	/**
	 * 下拉列表
	 */
	@GetMapping("/select")
	@ApiOperationSupport(order = 20)
	@ApiOperation(value = "下拉列表", notes = "传入trainingPlan")
	public R select(@ApiIgnore @RequestParam Map<String, Object>  entity) {
		QueryWrapper<PaperEntity> queryWrapper = Condition.getQueryWrapper(entity, PaperEntity.class);
		return R.data(paperService.list(queryWrapper));
	}


	/**
	 * 回收站
	 */
	@GetMapping("/paper-recycle-list")
	@ApiOperationSupport(order = 14)
	@ApiOperation(value = "试卷回收站分页", notes = "传入paper")
	public R paperRecycleList(PaperVO paper, Query query) {
		paper.setIsDeleted(1);
		IPage<PaperVO> pages = paperService.selectPaperPage(Condition.getPage(query), paper);
		return R.data(pages);
	}


	@GetMapping("/paper-restore")
	@ApiOperationSupport(order = 15)
	@ApiOperation(value = "恢复试卷", notes = "传入paper")
	public R paperRestore(Long id) {
		return R.data(paperService.paperRestore(id));
	}
}
